package com.gitee.jjnnzb.designpatterninspring.common.manager.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import com.gitee.jjnnzb.designpatterninspring.common.bean.CommonException;
import com.gitee.jjnnzb.designpatterninspring.common.manager.TokenManager;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author liletian
 * @since 2023-07-26 13:40
 */
@Service
public class TokenManagerImpl implements TokenManager {
    
    @Override
    public String getToken() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new CommonException("未知请求信息");
        }
        HttpServletRequest request = attributes.getRequest();
        String authorization = request.getHeader(Header.AUTHORIZATION.name());
        if (StringUtils.isBlank(authorization)) {
            throw new CommonException("未能获取请求Token");
        }
        return StrUtil.replaceIgnoreCase(authorization, "bearer ", Strings.EMPTY);
    }
}
